package main

import (
	"fmt"
	"sync"
	"time"
)

func main() {
	start := time.Now()

	concurrency := 10000

	var wg sync.WaitGroup
	wg.Add(concurrency)

	counter := &SafeCounter{}

	for i := 0; i < concurrency; i++ {
		go func(id int) {
			defer wg.Done()

			counter.Increment()
		}(i)
	}

	wg.Wait()

	elapsed := time.Since(start)
	fmt.Println("程序耗时:", elapsed)

	fmt.Println("result:", counter.Value())
}

type SafeCounter struct {
	mu    sync.Mutex
	count int
}

func (c *SafeCounter) Increment() {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.count++
}
func (c *SafeCounter) Value() int {
	c.mu.Lock()
	defer c.mu.Unlock()
	return c.count
}
